/*
登录路由模块
*/
const express = require('express')
const router = express.Router()
const path = require('path')
const db = require(path.join(__dirname, '../common/db.js'))
const utility = require('utility')
const jwt = require('jsonwebtoken')

//配置登录的路由地址
router.post('/login', async (req, res) => {
    //获取客户端传递的参数
    let params = req.body
    //对密码加密
    params.password = utility.md5(params.password)
    //查询数据库
    let sql = 'select id from user  where username= ? and password = ?'
    let ret = await db.operateData(sql, [params.username, params.password])
    if (ret && ret.length > 0) {
        let token = jwt.sign({
            username: params.username,
            id: ret[0].id
        }, 'bigevent', {
            expiresIn: '1h'
        })
        res.json({
            status: 0,
            message: '登录成功',
            token: 'Bearer ' + token
        })
    } else {
        res.json({
            status: 0,
            message: '登录成功'
        })
    }
})

//注册用户
router.post('/reguser', async (req, res) => {
    let sql = 'insert into user set ?'
    //前端传递参数
    let params = {
        username: req.body.username,
        password: utility.md5(req.body.password)
    }
    //插入数据库
    let ret = await db.operateData(sql, params)
    //返回状态
    if (ret && ret.affectedRows > 0) {
        res.json({
            status: 0,
            message: '注册成功'
        })
    } else {
        res.json({
            status: 1,
            message: '注册失败'
        })
    }
})


module.exports = router